package com.cloud.user.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author 李均华
 * @date 2021/6/21
 * @desc 自定义流量降级处理
 */
@Component
public class BasicBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("sentinel:");
        if (e instanceof FlowException) {
            stringBuilder.append("由于流量控制，访问被限制了");
        } else if (e instanceof ParamFlowException) {
            stringBuilder.append("由于参数限制，访问被限制了");
        } else if (e instanceof DegradeException) {
            stringBuilder.append("由于降级处理，访问被限制了");
        } else if (e instanceof AuthorityException) {
            stringBuilder.append("由于授权降级，访问被限制了");
        } else if (e instanceof SystemBlockException) {
            stringBuilder.append("由于系统负载降级，访问被限制了");
        }
        response.setStatus(429);
        StringBuffer url = request.getRequestURL();
        if (Objects.equals("GET",request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
            url.append("?").append(request.getQueryString());
        }
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(new String(stringBuilder));
        out.flush();
        out.close();
    }
}
